package com.atqar.tongxin;

/*有一个初始值为零的变量，现有两个线程对该变量操作，
实现一个线程对变量加1，实现一个线程对变量减1,交替来10轮*/


//线程  操作 支援
//判断  干活 通知

//v1加synchronized
/*
class ZhiYuan{
    int a =0;


    public synchronized void method1(){
        //判断
        //当有wait时必须要用while循环判断或者会造成虚假换行
        while (a!=0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        //干活
        System.out.println(Thread.currentThread().getName()+"="+(++a));
        //通知
        this.notifyAll();
    }

    public synchronized void method2(){
        //判断
        while (a==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        //干活
        System.out.println(Thread.currentThread().getName()+"="+(--a));
        //通知
        this.notifyAll();
    }
}*/


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//v2   Lock+condition.awit和signal方法
class ZhiYuan{
    int a=0;

    Lock lock=new ReentrantLock();
    Condition condition = lock.newCondition();

    public void method1(){
        lock.lock();
        try {
            while(a!=0){
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName()+"="+(++a));
            condition.signalAll();

        }finally {
            lock.unlock();
        }
    }
    public void method2(){
        lock.lock();
        try {
            while(a==0){
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName()+"="+(--a));
            condition.signalAll();

        }finally {
            lock.unlock();
        }
    }



}






public class ProduceConsumerDemo {
    public static void main(String[] args) {
        ZhiYuan zy =new ZhiYuan();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                zy.method1();
            }
        },"a").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                zy.method2();
            }
        },"b").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                zy.method1();
            }
        },"c").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                zy.method2();
            }
        },"d").start();



    }




}
